<?php

namespace Biz\service\brand;

use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandOrder;
use Biz\model\brand\BrandPackage;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\service\brandAccount\BrandAccount;
use Doraemon\tools\IdParse;

/**
 * 品牌认证服务
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BrandService
{
    /**
     * 获取所有品牌套餐列表
     * @return array
     */
    public static function getAllPackage()
    {
        $packages = BrandPackage::getAll();

        $data = [];
        foreach ($packages as $item) {
            $data[] = [
                'id' => IdParse::encryptUid($item['id']),
                'name' => $item['package_name'],
                'price' => $item['price'],
                'discount_price' => $item['discount_price'],
            ];
        }

        return $data;
    }

    public static function getPackage($brandId)
    {
        $result = [
            'current_pack_type' => 0,
            'package_list' => [],
            'default_pay_platform' => BrandOrder::PAY_PLATFORM_ALI_PAY,
            'pay_platform_list' => [
                'alipay' => Order::PAY_PLATFORM_ALIPAY,
                'wechat' => Order::PAY_PLATFORM_WECHAT,
            ],
            'sys_time' => date('Y-m-d H:i:s'),
            'new_package' => 1,
            'type' => BrandPackage::TYPE_ONLINE,
            'is_renewal' => 0,//是否可以续费（1:是0:否)
        ];
        $list = [];
        $brandInfo = mBrand::getBrandInfoById($brandId);
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brandId,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ]);
        $inStartTime = $accountInfo['in_start_time'] ?? '';
        $inEndTime = $accountInfo['in_end_time'] ?? '';
        if (!$inStartTime && !$inEndTime) {
            $inStartTime = date('Y-m-d');
            $inEndTime = date('Y-m-d', strtotime('+365day'));
        }
        $currentPackType = $brandInfo['pack_type'];//如果的当前套餐是自定义套餐，不支持用户自己开通
        if ($currentPackType >= BrandPackage::NEW_PACK_TYPE_START) {
            $result['current_pack_type'] = (int)$currentPackType;
            $result['type'] = BrandPackage::TYPE_OFFLINE;
            return $result;
        }

        $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($brandInfo['uid']);
        $hasUnUsedOrder = $hasUnUsedOrderRes[$brandInfo['uid']];
        //是否可以续费（不存在未生效的续费订单，临期60天并且有 审核通过-待使用的 认证信息）
        if ($hasUnUsedOrder) {
            $result['is_renewal'] = 0;
        } else if (BrandAccount::isBeforeExpire($accountInfo)) {
            $result['is_renewal'] = 1;
        }
        //如果可以续费，则套餐 展示为 未开通套餐的用户的所有套餐
        if ($result['is_renewal']) {
            $currentPackType = 0;
            $inStartTime = date('Y-m-d', strtotime($accountInfo['in_end_time']) + 86400);
            $inEndTime = date('Y-m-d', strtotime('+365day', strtotime($inStartTime)));
            $accountInfo = [];
        }

        $isNewPack = self::isNewPack($currentPackType);
        $result['new_package'] = $isNewPack;
        $packages = self::getPackList($currentPackType);
        $currentPackage = $currentPackType ? $packages[$currentPackType] : [];
        foreach ($packages as $row) {
            list($price, $isUpgrade, $isDiffPrice) = self::getPrice($currentPackage, $brandInfo, $row, $accountInfo);
            if ($isUpgrade && $row['pack_type'] != $currentPackType) {//升级套餐，有效期当天至入驻结束
                $inStartTime = date('Y-m-d');
            }
            $validTime = date('Y.m.d', strtotime($inStartTime)) . '-' . date('Y.m.d', strtotime($inEndTime));
            $list[] = [
                'package_id' => IdParse::encryptUid($row['id']),//套餐id
                'pack_type' => (int)$row['pack_type'],//套餐类型
                'name' => $row['package_name'],//套餐名称
                'price' => $price,//套餐支付价格
                'product_price' => $row['price'],//套餐售卖价格
                'is_upgrade' => (int)$isUpgrade,//是否可以升级（0：否 1：是）
                'is_diff_price' => $isDiffPrice,//是否补差价（0：否 1：是）
                'valid_time' => $validTime
            ];
        }
        $result['current_pack_type'] = (int)$brandInfo['pack_type'];
        $result['package_list'] = $list;
        return $result;
    }

    public static function getPrice($currentPackage, $brandInfo, $packageInfo, $accountInfo)
    {
        $isUpgrade = 0;
        $isDiffPrice = 0;
        $price = $packageInfo['discount_price'];
        $currentPackType = !empty($currentPackage) ? $currentPackage['pack_type'] : 0;
        if ($currentPackage && !empty($currentPackage)) {//当前有套餐
            $inEndTime = ($accountInfo && $accountInfo['in_end_time']) ? strtotime($accountInfo['in_end_time']) : 0;
            $todayTime = strtotime(date('Y-m-d'));
            $isUpgrade = self::isUpgradePack($currentPackType, $packageInfo['pack_type']);
            if ($isUpgrade) {
                $isUpgrade = 1;
                if ($inEndTime && $todayTime < $inEndTime) {//计算差价
                    $isDiffPrice = 1;
                    $dayPrice = ($packageInfo['discount_price'] - $currentPackage['discount_price']) / 365;
                    $day = abs(($inEndTime - $todayTime) / 86400);
                    $price = floor($dayPrice * $day);
                }
            }
        }
        return [$price, $isUpgrade, $isDiffPrice];
    }

    public static function getPackList($currentPackType)
    {
        if (self::isNewPack($currentPackType)) {
            $packList = BrandPackage::getNewPackList($currentPackType);
        } else {
            $packList = BrandPackage::getPackList();
        }
        return $packList;
    }

    public static function isUpgradePack($currentPackType, $packType)
    {
        $isUpgrade = false;
        $isNewPack = self::isNewPack($currentPackType);
        if ($isNewPack) {
            $upgradeArr = isset(BrandPackage::$newPackUpgrade[$currentPackType]) ? BrandPackage::$newPackUpgrade[$currentPackType] : [];
        } else {
            $upgradeArr = isset(BrandPackage::$packUpgrade[$currentPackType]) ? BrandPackage::$packUpgrade[$currentPackType] : [];
        }
        if ($upgradeArr && in_array($packType, $upgradeArr)) {
            $isUpgrade = true;
        }
        return $isUpgrade;
    }

    public static function getUpgradePackArr($currentPackType, $onlyNew = true)
    {
        $isNewPack = self::isNewPack($currentPackType);
        if ($isNewPack) {
            $upgradeArr = isset(BrandPackage::$newPackUpgrade[$currentPackType]) ? BrandPackage::$newPackUpgrade[$currentPackType] : [];
        } else if (!$onlyNew) {
            $upgradeArr = isset(BrandPackage::$packUpgrade[$currentPackType]) ? BrandPackage::$packUpgrade[$currentPackType] : [];
        }
        return $upgradeArr;
    }

    /**
     * 是否使用新套餐
     * @param $currentPackType
     */
    public static function isNewPack($currentPackType)
    {
        return in_array($currentPackType, BrandPackage::$packTypeList) ? 0 : 1;
    }

    /**
     * 是否可以升级套餐
     */
    public static function isRenewalPackage($brandInfo, $accountInfo)
    {
        $isRenewal = 0;
        //是否可以升级（临期60天，并且有审核通过的认证信息-非使用中的，是否存在未生效的续费订单）
        $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($brandInfo['uid']);
        $hasUnUsedOrder = $hasUnUsedOrderRes[$brandInfo['uid']];
        if ($hasUnUsedOrder) {
            $isRenewal = 0;
        } else if (BrandAccount::isBeforeExpire($accountInfo)) {

        }
        return $isRenewal;
    }

    public static function getPackageOption($brandId, $currPackType = 0)
    {
        $result = [];
        if (empty($currPackType)) {
            $where['OR'] = [
                'pack_type' => BrandPackage::$newPackTypeList,
                'pack_type[>=]' => BrandPackage::NEW_PACK_TYPE_START,
            ];
        } else if (isset(BrandPackage::$newPackUpgrade[$currPackType]) && BrandPackage::$newPackUpgrade[$currPackType]) {
            $where['pack_type'] = BrandPackage::$newPackUpgrade[$currPackType];
        }
        if (empty($where)) {
            return [];
        }
        $where['package_status'] = BrandPackage::STATUS_NORMAL;
        $currentPackage = BrandPackage::getInfoByPackType($currPackType);
        $brandInfo = mBrand::getInfo($brandId);
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brandId,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ]);
        $where['ORDER'] = ['pack_type' => 'ASC'];
        $packageList = BrandPackage::selectListByWhere($where);
        foreach ($packageList as $row) {
            list($price, $isUpgrade, $isDiffPrice) = self::getPrice($currentPackage, $brandInfo, $row, $accountInfo);
            if (in_array($row['pack_type'], [BrandPackage::PACK_CERTIFIED, BrandPackage::PACK_CERTIFIED_PLUS])) {
                $prefix = '认证账号';
            } else if ($row['type'] == BrandPackage::TYPE_ONLINE && $row['pack_type'] < BrandPackage::NEW_PACK_TYPE_START) {
                $prefix = '高级认证账号';
            } else {
                $prefix = BrandPackage::$types[$row['type']];
            }
            $result[$row['pack_type']] = '「' . $prefix . '-' . $row['package_name'] . '」原价¥' . $row['price'] . '需支付¥' . $price;
        }
        return $result;
    }
}